package com.h2cloud.depends;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * @author: wulongkai
 * @create: 2022-10-10 16:10
 **/
public class NetworkUtil {

    public static String IP_LIST = null;

    private static String getLocalIpListInner() throws SocketException {
        StringBuilder ipList = new StringBuilder();
        Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
        while (enumeration.hasMoreElements()) {
            NetworkInterface networkInterface = enumeration.nextElement();
            //排除回文地址和虚拟地址
            if (networkInterface.isLoopback() || networkInterface.isVirtual()) {
                continue;
            }
            Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                InetAddress addr = inetAddresses.nextElement();
                if (addr.isLoopbackAddress() || !addr.isSiteLocalAddress() || addr.isAnyLocalAddress()) {
                    continue;
                }
                ipList.append(addr.getHostAddress()).append("|");
            }
        }
        if (ipList.length() > 0) {
            return ipList.substring(0, ipList.length() - 1);
        }
        return "";
    }

    /**
     * 获取所有网卡IP（排除回文地址、虚拟地址）
     *
     * @return 所有网卡IP（排除回文地址、虚拟地址）
     * @throws SocketException 异常
     */
    public static String getLocalIpList() throws SocketException {
        if (null == IP_LIST) {
            synchronized (NetworkUtil.class) {
                if (null == IP_LIST) {
                    IP_LIST = getLocalIpListInner();
                }
            }
        }
        return IP_LIST;
    }
}

